package com.azdebugit.javasuanfa.test.kaifang;

import org.springframework.util.StopWatch;

/**
 * @Author: FLEAPX
 * @Date: 2021/5/27 11:05
 */
public class KaiFang1 {
    public static double sqrt (double c) {
        if (c < 0) {
            return Double.NaN;
        }
        double err = 1e-16;
        double temp = c;
        while (Math.abs(temp - c / temp) > err * temp) {
            temp = (c /temp + temp) / 2.0;
        }
        return temp;
    }

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        System.out.println("----：" + sqrt(256));
        stopWatch.stop();
        System.out.println("----：" +stopWatch.getTotalTimeMillis() );
        StopWatch stopWatch1 = new StopWatch();
        stopWatch1.start();
        System.out.println("----：" + MySqrt(256,1e-16));
        stopWatch1.stop();
        System.out.println("----：" +stopWatch1.getTotalTimeMillis() );
    }
    static double MySqrt(int value, double t){
        if (value < 0 || t<0)
            return 0;
        double left = 0;
        double right = value;
        double mid = (right + left) / 2;
        double offset = 2*t ;
        while (offset>t){
            double temp = mid*mid;
            if (temp > value){
                right = (left + right) / 2;
                offset = temp - value;
            }
            if (temp <= value){
                left = (left + right) / 2;
                offset = value - temp;
            }
            mid = (left + right) / 2;
        }
        return mid;
    }

}
